from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import QMainWindow, QWidget, QHBoxLayout, QVBoxLayout, QLabel, QPushButton, QListWidgetItem, QSize
from PyQt5.QtWidgets import QMessageBox
from connector.driver import DatabaseDriver
from tools import MessageBoxTools
from dao import BookDao, UserDao
from pages import LoginPage, ResetPasswordPage

class UserMainPage(QMainWindow):
    def __init__(self, user_id: int):
        super().__init__()
        self.user_id: int = user_id
        self.setupUi()
        self.show()
        self.get_borrow_books(self.user_id)
    def setupUi(self):
        self.setObjectName("MainWindow")
        self.resize(586, 534)
        self.label = QtWidgets.QLabel(self)
        self.label.setGeometry(QtCore.QRect(70, 50, 41, 9))
        self.label.setObjectName("label")
        self.pushButton = QtWidgets.QPushButton(self)
        self.pushButton.setGeometry(QtCore.QRect(230, 50, 56, 17))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self)
        self.pushButton_2.setGeometry(QtCore.QRect(380, 50, 56, 17))
        self.pushButton_2.setObjectName("pushButton_2")
        self.textBrowser = QtWidgets.QTextBrowser(self)
        self.textBrowser.setGeometry(QtCore.QRect(60, 190, 391, 281))
        self.textBrowser.setObjectName("textBrowser")
        self.textBrowser_2 = QtWidgets.QTextBrowser(self)
        self.textBrowser_2.setGeometry(QtCore.QRect(50, 100, 381, 31))
        self.textBrowser_2.setObjectName("textBrowser_2")
        self.pushButton_3 = QtWidgets.QPushButton(self)
        self.pushButton_3.setGeometry(QtCore.QRect(460, 110, 56, 17))
        self.pushButton_3.setObjectName("pushButton_3")

        self.retranslateUi(self)
        self.QMetaObject.connectSlotsByName(self)
        self.driver: DatabaseDriver = DatabaseDriver()
        self.get_user_info()
        self.get_books()
        # 绑定搜索按钮
        self.search_btn.clicked.connect(self.search_btn_clicked)
        # 绑定注销按钮
        self.logout_btn.clicked.connect(self.log_out_btn)
        # 绑定重置密码按钮
        self.reset_password_btn.clicked.connect(self.reset_password_btn_clicked)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.label.setText(_translate("Dialog", "欢迎你,"))
        self.pushButton.setText(_translate("Dialog", "重置密码"))
        self.pushButton_2.setText(_translate("Dialog", "注销"))
        self.pushButton_3.setText(_translate("Dialog", "搜索"))

    # 获取当前用户信息,并设置当前的欢迎词
    def get_user_info(self):
        user_info: tuple = UserDao.get_user_by_id(self.driver, self.user_id)
        if len(user_info) == 4:
            self.welcome_label.setText("欢迎您,{}".format(user_info[1]))
            self.user = user_info
        else:
            MessageBoxTools.warning("错误", "检索不到用户", buttons=QMessageBox.Ok)

    # 查询当前用户所有的代还的书籍
    def get_borrow_books(self, user_id: int):
        result: list = BookDao.get_borrow_books_by_user_id(self.driver, user_id)
        names = ["图书编号:", "借阅时间:", "图书名:", "作者:", "藏书地点:"]
        self.borrow_listview.clear()
        for borrow_book in result:
            # 设置一个新的item对象
            item = QListWidgetItem()
            # 设置这个item的固定大小
            item.setSizeHint(QSize(200, 100))
            # 设置widget,用于存储当前列表item的布局
            widget = QWidget()
            layout_main = QHBoxLayout()
            layout_main_left = QHBoxLayout()
            layout_main_left_1 = QVBoxLayout()
            l = QLabel()
            l.setText("{}{}\t{}{}\t{}{}\t{}{}\t{}{}".format(
                names[0], borrow_book[1], names[1], borrow_book[2], names[2],
                borrow_book[4], names[3], borrow_book[5],
                names[4], borrow_book[6]
            ))
            l.setStyleSheet("color: rgb(255, 255, 255);")
            layout_main_left_1.addWidget(l)
            layout_main_left.addLayout(layout_main_left_1)
            layout_main_right = QHBoxLayout()
            # 设置还书按钮
            borrow_book_btn = QPushButton()
            borrow_book_btn.setText("还书")
            borrow_book_btn.setFixedSize(QSize(60, 30))
            borrow_book_btn.setToolTip(str(borrow_book[1]))
            layout_main_right.addWidget(borrow_book_btn)
            layout_main.addLayout(layout_main_left)
            layout_main.addLayout(layout_main_right)
            widget.setLayout(layout_main)
            self.borrow_listview.addItem(item)
            self.borrow_listview.setItemWidget(item, widget)
        print(result)

    def get_books(self, result: tuple = None):
        if result is None:
            result: tuple = BookDao.get_all_books(self.driver)
        else:
            self.book_listview.clear()
        for r in result:
            item = QListWidgetItem()
            item.setSizeHint(QSize(200, 100))
            widget = QWidget()
            layout_main = QHBoxLayout()
            layout_main_left = QHBoxLayout()
            layout_main_left_1 = QVBoxLayout()
            layout_main_left_2 = QVBoxLayout()
            layout_main_left.addLayout(layout_main_left_1)
            layout_main_left.addLayout(layout_main_left_2)
            layout_main_right = QHBoxLayout()
            names = ["图书编号:", "图书名称:", "发行商:", "作者:", "分类:", "数量:", "藏书地点:"]
            for index, label in enumerate(r):
                l = QLabel()
                l.setText(names[index] + str(label))
                l.setStyleSheet("color: rgb(255, 255, 255);")
                if index > 3:
                    layout_main_left_2.addWidget(l)
                else:
                    layout_main_left_1.addWidget(l)
            borrow_book_btn = QPushButton()
            borrow_book_btn.setText("借书")
            borrow_book_btn.setFixedSize(QSize(60, 30))
            borrow_book_btn.setToolTip(str(r[0]))
            layout_main_right.addWidget(borrow_book_btn)
            layout_main.addLayout(layout_main_left)
            layout_main.addLayout(layout_main_right)
            widget.setLayout(layout_main)
            self.book_listview.addItem(item)
            self.book_listview.setItemWidget(item, widget)

    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
        self.driver.close()

    # 监听搜索按钮被按下的事件
    def search_btn_clicked(self):
        input_text = self.search_edit.text().strip()
        if input_text is "":
            MessageBoxTools.information(title="输入错误", text="请在搜索框中输入有效信息再进行搜索!",
                                        buttons=QMessageBox.Ok)
        else:
            result: tuple = None
            # 判断输入的是否是数字,如果是数字则认为是图书编号
            if input_text.isdigit():
                result = BookDao.user_search_books_by_book_id(self.driver, int(input_text))
            else:
                result = BookDao.user_search_books(self.driver, key=input_text)
            self.get_books(result)

    def log_out_btn(self):
        self.login_page = LoginPage.LoginPage()
        self.close()

    def reset_password_btn_clicked(self):
        self.reset_password_page = ResetPasswordPage.ResetPasswordPage(user_id=self.user_id, user_name=self.user[1])

    # 监听回车键被按下
    def keyPressEvent(self, key: QtGui.QKeyEvent) -> None:
        if key.key() == 16777220:
            # 判断按下的是否是回车键
            self.search_btn_clicked()
